import React from 'react'
import { connect } from 'react-redux'
import { List, Badge } from 'antd-mobile'
import { getPreyList } from '@/redux/Prey.redux'
import styles from './index.module.scss'
const Item = List.Item
const Brief = Item.Brief

@connect(
    state => ({
        user: state.user.user,
        chat: state.chat,
        prey: state.prey
    }),
    { getPreyList }
)
class ChatGroup extends React.Component{

    componentDidMount(){
        const { prey: { preyList } } = this.props
        if(!preyList.length)
            this.props.getPreyList()
    }

    render(){
        //1.过滤掉与自己无关的聊天，即group是否与包含我的userid
        const { user: { _id }, chat: { messages }, prey: {preyList}} = this.props
        let groupList = {}
        if(_id && preyList.length)
            messages.forEach(item => {
                if(item.group.indexOf(_id) !== -1){
                    if(!groupList[item.group])
                        groupList[item.group] = []
                    groupList[item.group].push(item)
                }
            })
        return preyList.length && _id ? (
            <div className={styles['chatGroup-container']}>
                {
                    Object.values(groupList)
                        .sort((a,b) => {
                            return b[b.length - 1].time - a[a.length - 1].time
                        })
                        .map(item => {
                            let last = item[item.length - 1]
                            let unRead = item.filter(i => !i.read && i.to === _id).length
                            let id = last.from === _id ? last.to : last.from
                            let user = preyList.find(item => item._id === id)
                            return (
                                <List key={user._id}>
                                    <Item
                                        extra={<Badge text={unRead}></Badge>}
                                        thumb={require(`@/assets/images/avatar/${user.avatar}.png`)}
                                        onClick={() => {
                                            this.props.history.push(`/chat/${user._id}`)
                                        }}
                                    >
                                        {user.username}
                                        <Brief>{last.content}</Brief>
                                    </Item>
                                </List>
                            )
                        })
                }
            </div>
        ) : null
    }
}

export default ChatGroup